package com.ly.hotel.util;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

	private static final int REQUEST_TIMEOUT = 1000 * 10;
	private static final int SO_TIMEOUT = 1000 * 10;

	public static String get(String url) {
		String strResult = "";
		/* URL可以随意改 */
		/* 建立HTTP Get对象 */
		HttpClient client = new DefaultHttpClient();
		HttpParams params = client.getParams();
		HttpGet httpRequest = new HttpGet(url);
		setAgent(httpRequest);
		try {
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = client.execute(httpRequest);

			HttpConnectionParams.setConnectionTimeout(params, 1000 * 5);
			HttpConnectionParams.setSoTimeout(params, 1000 * 5);

			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读 */
				strResult = EntityUtils.toString(httpResponse.getEntity());
			} else {
				return strResult;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strResult;
	}

	public static String requestGet(String url, List<NameValuePair> params,
			Integer reqTimeOut, Integer soTimeOut) {
		try {
			int req = REQUEST_TIMEOUT;
			int so = SO_TIMEOUT;
			if (reqTimeOut != null) {
				req = reqTimeOut;
			}
			if (soTimeOut != null) {
				so = soTimeOut;
			}
			String strParams = "";
			if (params != null && !params.isEmpty()) {
				strParams = URLEncodedUtils.format(params, "utf-8");
			}
			if (url.indexOf("?") == -1) {
				url = url + "?";
			} else {
				if (!strParams.equals("")) {
					url += "&";
				}
			}
			HttpGet get = new HttpGet(url + strParams);
			setAgent(get);
			return executeRequest(createHttpClient(req, so), get);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}



	public static String requestPost(String url, List<NameValuePair> params, Integer reqTimeOut, Integer soTimeOut){
		try {
			int req = REQUEST_TIMEOUT;
			int so = SO_TIMEOUT;
			if(reqTimeOut != null){
				req = reqTimeOut;
			}
			if(soTimeOut != null){
				so = soTimeOut;
			}
			HttpPost post = new HttpPost(url);
			setAgent(post);
			if(params != null && !params.isEmpty()){
				post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			}
			return executeRequest(createHttpClient(req, so), post);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static String executeRequest(HttpClient httpClient, HttpUriRequest url){
		try {
			HttpResponse response = httpClient.execute(url);
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				return EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static HttpClient createHttpClient(int reqTimeOut, int soTimeOut) {
		BasicHttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, reqTimeOut);
		HttpConnectionParams.setSoTimeout(params, soTimeOut);
		SchemeRegistry chReg = new SchemeRegistry();
		chReg.register(new Scheme("http",
				PlainSocketFactory.getSocketFactory(), 80));
		chReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(),
				443));
		ClientConnectionManager conMnger = new ThreadSafeClientConnManager(
				params, chReg);
		return new DefaultHttpClient(conMnger, params);
	}
	
	private static void setAgent(HttpRequestBase request) {
		request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rc:30.0) Gccko/20100101 Firefox/30.0");
	}

}
